#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : client.py
@Author  : lepal
@Time    : 2024-08-13 14:25
"""
from flask import request

from app.libs.RedPrint import RedPrint
from app.libs.enums import ClientTypeEnum
from app.models.user import User
from app.validators.forms import ClientForm, UserEmailForm
from app.libs.error_code import ClientTypeError, Success


api = RedPrint('client')

@api.route('/register', methods=['POST'])
def register():
    # if request.is_json:   #  如果不判断，而且没有传递body参数的话，直接访问 request.json 会报错
    #     data = request.get_json()
    #     print(data)
    #
    # if request.args:
    #     print(request.args.to_dict())


    # 重写新增validators/base.py前的写法 ===========
    # # 获取参数
    # data = request.json
    # # 验证参数
    # form = ClientForm(data = data)  # 如果是json格式，要对应一个data的键名，这个是wtforms的用法

    # if form.validate(): # 如果验证通过
    #     promise = {
    #         ClientTypeEnum.USER_EMAIL: __register_user_by_email, # 如果是邮件注册
    #         # ClientTypeEnum.USER_MOBILE: __register_by_user_mobile, # 如果是手机注册
    #     }
    #
    #     # 调用对应的方法
    #     promise[form.type.data]()
    # else: # 验证失败
    #     print(form.errors) # {'type': ['99 is not a valid ClientTypeEnum']}
    #     raise ClientTypeError()


    # 新增validators/base.py 后的写法，这里不用捕获form.validate()的错误 ===========
    # # 获取参数
    # data = request.json
    # # 验证参数
    # form = ClientForm(data=data)  # 如果是json格式，要对应一个data的键名，这个是wtforms的用法
    # # 优化增加validator/base.py后改写，如果没验证通过会自己跑出错误
    # form.validate_for_api()
    # promise = {
    #     ClientTypeEnum.USER_EMAIL: __register_user_by_email, # 如果是邮件注册
    #     # ClientTypeEnum.USER_MOBILE: __register_by_user_mobile, # 如果是手机注册
    # }
    # # 调用对应的方法
    # promise[form.type.data]()


    # 继续优化参数，优化让调用用方法更简洁后
    form = ClientForm().validate_for_api()
    promise = {
        ClientTypeEnum.USER_EMAIL: __register_user_by_email,  # 如果是邮件注册
        # ClientTypeEnum.USER_MOBILE: __register_by_user_mobile, # 如果是手机注册
    }
    # 调用对应的方法
    promise[form.type.data]()

    return Success()


def __register_user_by_email():
    form = UserEmailForm().validate_for_api()
    User.register_by_email(form.nickname.data,
                           form.account.data,
                           form.secret.data)
